package com.iwjw.ibatis.plugins.dynamic;

import com.iwjw.ibatis.annotations.MasterMark;
import com.iwjw.ibatis.mapper.ISqlInjector;
import com.iwjw.ibatis.plugins.dynamic.spring.DynamicDataSourceGlobal;
import com.iwjw.ibatis.plugins.dynamic.spring.DynamicDataSourceHolder;
import com.iwjw.ibatis.plugins.dynamic.spring.aop.MasterSynchronizationManager;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.keygen.SelectKeyGenerator;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 读写拦截器
 *
 * @author: huangweiwei
 * @email: ihuangweiwei@163.com
 * @created:2016/10/25
 */
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {
                MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {
                MappedStatement.class, Object.class, RowBounds.class,
                ResultHandler.class})})
public class DynamicPlugin implements Interceptor {

    protected static final Logger logger = LoggerFactory.getLogger(DynamicPlugin.class);

    private static final String REGEX = ".*insert\\u0020.*|.*delete\\u0020.*|.*update\\u0020.*";

    public Object intercept(Invocation invocation) throws Throwable {
        logger.debug("current Thread name:{}", Thread.currentThread().getName());
        //如果强制走了主库

        boolean isMaster = MasterSynchronizationManager.isMasterActive();
        if (isMaster) {
            DynamicDataSourceHolder.putDataSource(DynamicDataSourceGlobal.WRITE);
            return invocation.proceed();
        }
        boolean synchronizationActive = TransactionSynchronizationManager.isSynchronizationActive();
        if (synchronizationActive) {
            DynamicDataSourceHolder.putDataSource(DynamicDataSourceGlobal.WRITE);
            return invocation.proceed();
        }

        Object[] objects = invocation.getArgs();
        MappedStatement ms = (MappedStatement) objects[0];
        DynamicDataSourceGlobal dynamicDataSourceGlobal = null;
        //读方法
        if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
            //!selectKey 为自增id查询主键(SELECT LAST_INSERT_ID() )方法，使用主库
            if (ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
                dynamicDataSourceGlobal = DynamicDataSourceGlobal.WRITE;
            } else {
                BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
                String sql = boundSql.getSql().toLowerCase(Locale.CHINA).replaceAll("[\\t\\n\\r]", " ");
                if (sql.matches(REGEX)) {
                    dynamicDataSourceGlobal = DynamicDataSourceGlobal.WRITE;
                } else {
                    //默认读肯定走从库库
                    dynamicDataSourceGlobal = DynamicDataSourceGlobal.READ;
                    //读的情况走主库，有MasterMark注解类
                    Object obj = boundSql.getParameterObject();
                    if (obj instanceof MapperMethod.ParamMap) {
                        Map<String,Object> params = (Map) obj;
                        if (params.keySet().contains(ISqlInjector.MASTER_MARK) && ((MasterMark[]) params.get(ISqlInjector.MASTER_MARK)).length>0) {
                            dynamicDataSourceGlobal = DynamicDataSourceGlobal.WRITE;
                        }
                    }

                }
            }
        }
         if(dynamicDataSourceGlobal==null){
             dynamicDataSourceGlobal = DynamicDataSourceGlobal.WRITE;
         }
        DynamicDataSourceHolder.putDataSource(dynamicDataSourceGlobal);
        return invocation.proceed();
    }

    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    public void setProperties(Properties properties) {

    }
}
